// 路由拦截

import store from '@/store/index.js'
import router, { asyncRoutes, defaultRoutes } from './index'
import { getToken } from '@/utils/app'
import { getPermissionsMenus } from '@/api/login/index.js'
import { filterAsyncRoutes, correctRedirect } from '@/utils/app'
import { cloneDeep } from 'lodash'

/* 按钮级别权限-自定义指令 */

// 拦截白名单 登录
const whiteRouter = ['/login']
localStorage.setItem('flag', false)

// 权限处理
router.beforeEach(async (to, from, next) => {
  console.log(to)

  // 如果有token则表示已经登录则不能再返回登录页面
  if (getToken()) {
    // 如果权限信息为空数组则重新去获取权限 避免重复请求
    if (store.state.newAsyncRoutes.length === 0) {
      // 获取用户权限
      console.log('account', store.state.account)

      const res = await getPermissionsMenus(store.state.account)
      console.log('getPermissionsMenus', res.object)
      // 存储到vuex
      store.commit('setNewAsyncRoutes', res.object)
      // console.log("setNewAsyncRoutes", res.object);
      // 过滤异步路由表
      const newAsyncRoutes = filterAsyncRoutes(store.state.newAsyncRoutes, cloneDeep(asyncRoutes))
      console.log('newAsyncRoutes', newAsyncRoutes)

      correctRedirect(newAsyncRoutes)

      // 添加404 一点得是数组最后
      newAsyncRoutes.push({
        path: '/:catchAll(.*)',
        redirect: '/404',
        hidden: true
      })
      // 连接默认路由表和异步路由并存储到vuex 用于菜单栏渲染
      console.log('最后的路由', defaultRoutes.concat(newAsyncRoutes))
      store.commit('setMenus', defaultRoutes.concat(newAsyncRoutes))
      /* store.commit("setMenus", [
        {
          path: "/console",
          name: "Console",
          meta: {
            title: "首页",
            hidden: false,
          },
          title: "首页",
          redirect: "/home",
          component: () => import("@/components/layout/BasicLayout.vue"),
          children: [
            {
              path: "/home",
              name: "Home",
              meta: {
                title: "首页",
                hidden: false,
              },
              component: () => import("@/views/Home.vue"),
            },
          ],
        },
        // 企业邮箱
        {
          path: "/email",
          name: "Email",
          meta: {
            title: "企业邮箱",
            hidden: false,
          },
          redirect: "/email/all",
          component: () => import("@/components/layout/BasicLayout.vue"),
          children: [
            {
              path: "/email/all",
              name: "EmailAll",
              meta: {
                title: "企业邮箱",
                hidden: false,
              },
              component: () => import("@/components/layout/RouterView.vue"),
              redirect: "/email/all/look",
              children: [
                {
                  path: "/email/all/look",
                  name: "EmailAllLookList",
                  meta: {
                    title: "收件箱",
                    hidden: false,
                  },
                  component: () =>
                    import("@/views/email/all/look/email-list.vue"),
                },
                {
                  path: "/email/all/look",
                  name: "EmailAllLookDetail",
                  meta: {
                    title: "邮件详情",
                    hidden: true,
                  },
                  component: () =>
                    import("@/views/email/all/look/email-detail.vue"),
                },
                {
                  path: "/email/all/write",
                  name: "EmailWrite",
                  meta: {
                    title: "写邮件",
                    hidden: false,
                  },
                  component: () =>
                    import("@/views/email/all/write/email-write.vue"),
                },
                {
                  path: "/email/all/succ",
                  name: "EmailSuccList",
                  meta: {
                    title: "已发送",
                    hidden: false,
                  },
                  component: () =>
                    import("@/views/email/all/succ/succ-list.vue"),
                },
              ],
            },
          ],
        },
        ...newAsyncRoutes,
      ]); */
      //[{首页那一堆},...newAsyncRouter]
      console.log('newAsyncRoutes', newAsyncRoutes)
      // console.log('excludeEmpty',excludeEmpty(newAsyncRoutes));
      // 添加路由
      newAsyncRoutes.forEach(item => {
        router.addRoute(item)
      })
      console.log('to.path', to.path)
      // 解决退出登录后再次登录跳转404问题
      if (from.path === '/login') {
        next('/home')
      }
      //重进一次 解决白屏
      next({ ...to, replace: true })
      console.log('router', router.getRoutes())
    }
    // console.log(4545454544545);
    if (to.path === '/login') {
      next('/')
    } else {
      next()
    }
  } else {
    // 未登录则只能访问白名单页面 访问白名单以外的页面则跳转到登录页
    if (whiteRouter.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})

/*

检查用户权限函数
页面中这样使用
v-if="checkPermission(['editor'])"
*/

export function checkPermission(value) {
  if (value && value instanceof Array && value.length > 0) {
    const roles = store.getters && store.getters.roles

    const permissionRoles = value

    const hasPermission = roles.some(role => {
      return permissionRoles.includes(role)
    })
    return hasPermission
  } else {
    console.error(`need roles! Like v-permission="['admin','editor']"`)
    return false
  }
}
